/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.CA_Service;
import model.CertificateDAO;
import model.KeyIO;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;

/**
 *
 * @author XuanTuan
 */
public class CreateCertControl extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, InvalidKeyException, NoSuchProviderException, SignatureException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");


        MultipartRequest mt = null;
        String encType = "utf-8";
        String folder = getServletContext().getRealPath("\\PublicKey");
        int maxSize = 5 * 1024 * 1024;


        mt = new MultipartRequest(request, folder, maxSize, encType,
                new DefaultFileRenamePolicy());
        String CN = mt.getParameter("CN");
        String OU = mt.getParameter("OU");
        String O = mt.getParameter("O");
        String L = mt.getParameter("L");
        String C = mt.getParameter("C");
        String filePath = folder + "\\" + mt.getParameter("filename");

        request.setAttribute("CN", CN);
        request.setAttribute("OU", OU);
        request.setAttribute("O", O);
        request.setAttribute("L", L);
        request.setAttribute("C", C);
        boolean check = true;
        if (CN.equals("")) {
            request.setAttribute("errorCreate", "Please input your Common Name!");
            check = false;
        } else if (OU.equals("")) {
            request.setAttribute("errorCreate", "Please input your Oganazational Unit!");
            check = false;
        } else if (O.equals("")) {
            request.setAttribute("errorCreate", "Please input your Oganazation!");
            check = false;
        } else if (L.equals("")) {
            request.setAttribute("errorCreate", "Please input your Locality");
            check = false;
        } else if (C.equals("")) {
            request.setAttribute("errorCreate", "Please input your Country!");
            check = false;
        } else if (mt.getParameter("filename").equals("")) {
            request.setAttribute("errorCreate", "Please Choose your Public key to upload!");
            check = false;
        }

        if (check == false) {
            RequestDispatcher dispatcherObject = getServletContext().getRequestDispatcher("/CreateCert.jsp");
            dispatcherObject.forward(request, response);
            return;
        }

        //create cert
        X500Name subject = new X500Name("CN=" + CN + ", OU=" + OU + ", O=" + O + ", L=" + L + ", C=" + C);
        FileInputStream priKeyFile = new FileInputStream(getServletContext().getRealPath("\\CAKeys") + "\\pri");
        PrivateKey privateKey = KeyIO.getPrivateKey(priKeyFile);
        File pubKey = new File(filePath);
        FileInputStream pubKeyFile = new FileInputStream(pubKey);

        PublicKey publicKey = null;
        try {
            publicKey = KeyIO.getPublicKey(pubKeyFile);
        } catch (Exception ex) {
            request.setAttribute("errorCreate", "Public key is not valid!");
            RequestDispatcher dispatcherObject = getServletContext().getRequestDispatcher("/CreateCert.jsp");
            dispatcherObject.forward(request, response);
            return;
        }

        X509CertImpl cert = CA_Service.createCert(subject, privateKey, publicKey);

        //save cert to server
        String certName = "Certificates/" + cert.getSerialNumber() + "_" + CN + ".cer";
        String certPath = getServletContext().getRealPath("\\Certificates") + "\\" + cert.getSerialNumber() + "_" + CN + ".cer";
        FileOutputStream fileOutputStream = new FileOutputStream(certPath);
        fileOutputStream.write(cert.getEncoded());
        fileOutputStream.close();

        //delete pub key file
        priKeyFile.close();
        pubKeyFile.close();
        pubKey.delete();

        //create database entry
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("user");
        boolean bo = CertificateDAO.addCert(cert.getSerialNumber() + "", username, cert.getNotAfter(), cert.getNotBefore(), certPath, certName);
        System.out.println(bo);

        request.setAttribute("info", "Certificate created successful!<br/> Click <a href=\"/VeriSignCA/Certificates/" + cert.getSerialNumber() + "_" + CN + ".cer\">Here</a> to download!");
        RequestDispatcher dispatcherObject = getServletContext().getRequestDispatcher("/info.jsp");
        dispatcherObject.forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignatureException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SignatureException ex) {
            Logger.getLogger(CreateCertControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
